<template>
  <el-form :model="form" :rules='rules' ref="formRef" label-width="140px">
    <el-row :gutter="10">
      <el-col :span="6">
        <el-form-item label="登记时间">
          <el-input v-model="form.djsj" disabled/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="投诉渠道" prop="tsqdVal">
          <el-select v-model="form.tsqdVal" placeholder="请选择" clearable>
            <el-option
                v-for="item in options.tsqd"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="投诉客户对接渠道" prop="tskhdjqdVal">
          <el-select v-model="form.tskhdjqdVal" placeholder="请选择" clearable>
            <el-option
                v-for="item in options.tskhdjqd"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="投诉问题发生时间" clearable prop="tswtfssj">
          <DateTimePicker v-model="form.tswtfssj"/>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="10">
      <el-col :span="6">
        <el-form-item label="投诉客户对接群名" prop="tskhdjqm">
          <el-input v-model="form.tskhdjqm" clearable/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="违规问题分部一" prop="wgwtfbyVal">
          <el-select v-model="form.wgwtfbyVal" placeholder="请选择" clearable>
            <el-option
                v-for="item in options.wgwtfby"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="违规问题分部二" prop="wgwtfbeVal">
          <WtfbeSelect :parent-id="form.wgwtfbyVal" v-model="form.wgwtfbeVal"></WtfbeSelect>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="处理人" prop="zdclry">
          <YwdjrSelect v-model="form.zdclry"></YwdjrSelect>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="24">
        <el-form-item label="关键词" style="width: 1500px" prop="gjc">
          <el-input v-model="form.gjc" clearable/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="24">
        <el-form-item label="问题描述" style="width: 1500px" prop="wtms">
          <el-input v-model="form.wtms" type="textarea" :rows="4" clearable/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="6">
        <el-form-item style="width: 500px; height: 20px">
          <el-upload
              ref="upload"
              :headers="uploadHeaders"
              :on-change="handleChange"
              :auto-upload="false"
              :on-progress="onProgress"
              multiple
              v-model:file-list="filesList"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <el-button style="margin-left: 10px" type="danger" @click="deleteUpload">清空文件</el-button>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <custom-file-upload style="margin-left: 0px" @files-selected="onFilesSelected"></custom-file-upload>
      </el-col>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="2" style="margin-left: 1100px">
        <el-form-item>
          <el-button type="primary" style="width: 100px" @click="onSubmit">提交</el-button>
        </el-form-item>
      </el-col>
      <el-col :span="2">
        <el-form-item>
          <el-button style="width: 100px" @click="onCancel">取消</el-button>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import {getTskhqd} from "@/views/menus/n-customer-complaint-sjkb-new/api.ts";
import DateTimePicker from "@/views/menus/n-customer-complaint-registration-new/components/DateTimePicker.vue";
import YwdjrSelect from "@/views/menus/n-customer-complaint-registration-new/components/YwdjrSelect.vue";
import WtfbeSelect from "@/views/menus/n-customer-complaint-registration-new/components/wtfbeSelect.vue";
import CustomFileUpload from "@/views/menus/n-customer-complaint-registration-new/components/CustomFileUpload.vue";
import type {FormItemRule, UploadInstance} from 'element-plus'
import {postUploadFile} from "@/views/menus/n-customer-complaint-registration-new/api.ts";

const formRef = ref()

const onProgress = (evt: ProgressEvent) => {
  console.log(evt)
}
/*文件上传*/
const uploadHeaders = ref({token: localStorage.getItem('token')})

const upload = ref<UploadInstance>();
//系统的文件上传
const fileList = ref<File[]>([])

// 手动维护 filesList，用于绑定到 el-upload
const filesList = ref<any[]>([]);

const onFilesSelected = (files: File[]) => {
  //处理选中的文件
  console.log('Selected files', files);

  if (files.length > 0) {
    files.forEach(file => {
      console.log('file', file)
      upload.value?.handleStart(file)
    })
  }
}

// 表单初始值
const form = reactive({
  djsj: '',
  tsqdVal: '',
  tskhdjqdVal: '',
  tswtfssj: '',
  tskhdjqm: '',
  wgwtfbyVal: '',
  wgwtfbeVal: '',
  zdclry: '',
  gjc: '',
  wtms: '',
  cjr: '',
})

const emit = defineEmits<{
  (e: 'submit'): void
  (e: 'cancel'): void
}>()

const onSubmit = async () => {
  upload.value!.submit()
  upload.value!.clearFiles()
  const valid = await formRef.value.validate()
  if (valid) {
    const formData = {
      djsj: form.djsj,
      tsqd: form.tsqdVal,
      tskhdjqd: form.tskhdjqdVal,
      tswtfssj: form.tswtfssj,
      tskhdjqm: form.tskhdjqm,
      wgwtfby: form.wgwtfbyVal,
      wgwtfbe: form.wgwtfbeVal,
      zdclry: form.zdclry,
      gjc: form.gjc,
      wtms: form.wtms,
    }
    const res = postUploadFile(formData, fileList.value)
    console.log('res', res)
    emit('submit')
  }
}

const onCancel = () => {
  emit('cancel')
}

const handleChange = (file: any, fileListParam: any[]) => {
  filesList.value = fileListParam;
  if (file.raw) {
    fileList.value.push(file.raw as File)
  }
}

const deleteUpload = () => {
  upload.value!.clearFiles()
  fileList.value = []
}

const dictIds = {
  tsqd: 63, // 投诉渠道
  tskhdjqd: 28, // 投诉客户对接渠道
  wgwtfby: 64, // 违规问题分部一
}
const options = reactive({
  tsqd: [],
  tskhdjqd: [],
  wgwtfby: [],
})

// 封装通用方法来根据 dictId 获取选项数据
const fetchOptions = async (dictKey: keyof typeof dictIds) => {
  try {
    const dictId = dictIds[dictKey]
    const data = await getTskhqd({dictId})
    options[dictKey] = data.map((item: any) => ({
      label: item.name,
      value: item.val
    }))
  } catch (error) {
    console.error('获取数据失败：', error)
  }
}

const rules = reactive<{ [K in keyof typeof form]?: Array<FormItemRule> }>({
  tsqdVal: [
    {required: true, message: '请选择投诉渠道', trigger: 'change'},
  ],
  tskhdjqdVal: [
    {required: true, message: '请选择投诉客户对接渠道', trigger: 'change'},
  ],
  tswtfssj: [
    {required: true, message: '请选择投诉时间', trigger: 'change'},
  ],
  tskhdjqm: [
    {required: true, message: '请填写投诉客户对接描述', trigger: 'blur'},
  ],
  wgwtfbyVal: [
    {required: true, message: '请选择违规问题分部一', trigger: 'change'}
  ],
  wgwtfbeVal: [
    {required: true, message: '请选择违规问题分部二', trigger: 'change'}
  ],
  zdclry: [
    {required: true, message: '请填写处理人', trigger: 'change'},
  ],
  gjc: [
    {
      validator: (rule, value, callback) => {
        if (!value && !form.wtms) {
          callback(new Error('关键词 和 问题描述 至少填写一个'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  wtms: [
    {
      validator: (rule, value, callback) => {
        if (!value && !form.gjc) {
          callback(new Error('关键词 和 问题描述 至少填写一个'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

onMounted(async () => {
  await Promise.all([
    fetchOptions('tsqd'),
    fetchOptions('tskhdjqd'),
    fetchOptions('wgwtfby'),
  ])
})
</script>

<style scoped lang="scss">
.el-form-item {
  width: 350px;
}
</style>

